Page({
  data: {
    isRotating: false,
    awards: [
      '一等奖', '二等奖', '三等奖', '四等奖', '五等奖', '谢谢惠顾'
    ],
    awardProb: [0.001, 0.005, 0.03, 0.10, 0.25, 0.614],
    colors: ['#FFEB3B', '#FF9800', '#FFEB3B', '#FF9800', '#FFEB3B', '#FF9800'],
    wheelSize: 400, // px
    pointerAngle: 0
  },
  onReady() {
    this.drawWheel(0);
  },
  drawWheel(angle = 0) {
    const awards = this.data.awards;
    const colors = this.data.colors;
    const ctx = wx.createCanvasContext('wheelCanvas', this);
    const num = awards.length;
    const size = this.data.wheelSize;
    const r = size / 2;
    ctx.save();
    ctx.clearRect(0, 0, size, size);
    ctx.translate(r, r);
    ctx.rotate(angle * Math.PI / 180);
    for (let i = 0; i < num; i++) {
      ctx.save();
      ctx.beginPath();
      ctx.moveTo(0, 0);
      ctx.arc(0, 0, r, i * 2 * Math.PI / num, (i + 1) * 2 * Math.PI / num);
      ctx.setFillStyle(colors[i % colors.length]);
      ctx.fill();
      ctx.restore();
      // 奖项文字横向居中
      ctx.save();
      ctx.rotate((i + 0.5) * 2 * Math.PI / num);
      ctx.translate(r * 0.55, 0);
      ctx.rotate(Math.PI / 2);
      ctx.setFillStyle('#333');
      ctx.setFontSize(20);
      ctx.setTextAlign('center');
      ctx.setTextBaseline('middle');
      ctx.fillText(awards[i], 0, 0);
      ctx.restore();
    }
    ctx.restore();
    // 画指针
    ctx.save();
    ctx.translate(r, r);
    ctx.beginPath();
    ctx.moveTo(0, -r + 10);
    ctx.lineTo(-12, -r + 40);
    ctx.lineTo(12, -r + 40);
    ctx.closePath();
    ctx.setFillStyle('#e53935');
    ctx.fill();
    ctx.restore();
    ctx.draw();
  },
  getAwardIndexByProb() {
    const prob = this.data.awardProb;
    const rand = Math.random();
    let sum = 0;
    for (let i = 0; i < prob.length; i++) {
      sum += prob[i];
      if (rand < sum) return i;
    }
    return prob.length - 1;
  },
  startDraw() {
    if (this.data.isRotating) return;
    this.setData({ isRotating: true });
    const awards = this.data.awards;
    const num = awards.length;
    // 按概率抽奖
    const idx = this.getAwardIndexByProb();
    // 计算目标角度
    const perAngle = 360 / num;
    const targetAngle = 360 * 5 + (270 - idx * perAngle - perAngle / 2); // 多转几圈+指针指向奖项
    let start = 0;
    const duration = 3000;
    const frame = 100;
    const interval = duration / frame;
    let count = 0;
    const animate = () => {
      count++;
      // ease out
      const progress = count / frame;
      const ease = 1 - Math.pow(1 - progress, 3);
      const angle = start + (targetAngle - start) * ease;
      this.drawWheel(angle % 360);
      if (count < frame) {
        setTimeout(animate, interval);
      } else {
        this.setData({ isRotating: false });
        wx.showToast({ title: `恭喜获得${awards[idx]}`, icon: 'none' });
      }
    };
    animate();
  },
  goBack() {
    wx.navigateBack();
  }
}); 